package com.wbao.dianniu.ui;


import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMManager;
import com.tencent.qcloud.timchat.utils.LoginBusiness;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.ClearEditText;
import com.wbao.dianniu.customView.LoadingDialog;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.data.LoginResponse;
import com.wbao.dianniu.http.ErrorCode;
import com.wbao.dianniu.listener.ILoginListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.GlobalUserData;
import com.wbao.dianniu.logical.SharedPreferencesUtils;
import com.wbao.dianniu.manager.LoginManager;
import com.wbao.dianniu.utils.ActivityUtils;
import com.wbao.dianniu.utils.KeyboardHeightHandler;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.Utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 登录
 *
 * @author yejianjun
 */
public class LoginActivity extends Activity implements ILoginListener, TIMCallBack {

    private static final String TAG = LoginActivity.class.getSimpleName();
    private Button loginBtn;
    private ClearEditText mUserText, mPasswordText;
    private TextView registerTV, forgetTV;
    private LoginManager manager;
    private Dialog pDialog;
    private TextView msgLoginTV;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ActivityUtils.setStatusBarColor(this);

        init();
        manager = new LoginManager(this);
        manager.addLoginListener(this);
        if (0 == SharedPreferencesUtils.getKeyboardHeight(this)) {
            KeyboardHeightHandler handler = new KeyboardHeightHandler();
            handler.getKeyboardHeight(this);
        }
    }

    private void init() {
        loginBtn = findViewById(R.id.login_btn);
        mUserText = findViewById(R.id.username);
        mPasswordText = findViewById(R.id.password);
        registerTV = findViewById(R.id.login_register);
        forgetTV = findViewById(R.id.login_forgetPassword);
        msgLoginTV = findViewById(R.id.message_login);
        loginBtn.setOnClickListener(noDoubleClickListener);
        registerTV.setOnClickListener(noDoubleClickListener);
        forgetTV.setOnClickListener(noDoubleClickListener);
        msgLoginTV.setOnClickListener(noDoubleClickListener);
        mPasswordText.setTransformationMethod(PasswordTransformationMethod.getInstance());
    }

    private void login() {
        String username = mUserText.getText().toString().trim();
        String password = mPasswordText.getText().toString().trim();

        // 判断用户名
        if (null == username) {
            Notification.toast(LoginActivity.this, getResources().getString(R.string.login_error_2));
        } else if (null == password) {
            Notification.toast(LoginActivity.this, getResources().getString(R.string.login_error_3));
        } else {
            //密码不能输入中文
            Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
            Matcher matcher = p.matcher(password);
            if (matcher.find()) {
                Notification.toast(LoginActivity.this, getResources().getString(R.string.register_error_8));
                mPasswordText.setText("");
                return;
            }

            /** 是否为手机号码 */
            boolean ismobile = username.matches("^(13|15|18|14|17)\\d{9}$");
            if (!ismobile) {
                Notification.toast(LoginActivity.this, getResources().getString(R.string.login_error_1));
                return;
            }
            showWaittingDialog();
            String longitude = SharedPreferencesUtils.getLongitude(this);
            String latitude = SharedPreferencesUtils.getLatitude(this);
            String pushClientId = SharedPreferencesUtils.getClientId(this);
            // 发送登录请求
            manager.Login(this, username, Utils.Md5(password), Utils.getDeviceId(this), longitude, latitude, Utils.getVersionName(LoginActivity.this), null, pushClientId);
        }

    }

    private void showWaittingDialog() {
        pDialog = LoadingDialog.createLoadingDialog(this, "正在登录...");
        pDialog.show();
    }


    @Override
    public void onLoginFailure(int errorCode, String errorMsg) {
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        // 登录失败-----
        if (errorCode == ErrorCode.PASSWORD_ERRORCODE) {
            int count = SharedPreferencesUtils.getLoginErrorCount(this);
            count++;
            SharedPreferencesUtils.setLoginErrorCount(this, count);
        }
        Notification.toast(this, errorMsg == null ? "" : errorMsg);

    }

    @Override
    public void onLoginSuccess(LoginResponse objdata) {
        /** 清除登录错误次数累加	*/
        SharedPreferencesUtils.setLoginErrorCount(this, 0);
        Utils.saveLoginData(this, objdata);
        // 保存自动登录配置信息
        saveConfigInfo();
        // 先保存用户数据再调登录im
        LoginBusiness.loginIm(objdata.getEnvironmentName() + objdata.getAccountInfo().getId(), objdata.getTencentImUserSig(), this);

    }

    private void intoMainActivity() {
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        // 成功 界面跳转
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.setClass(LoginActivity.this, MainActivity.class);
        startActivity(intent);
        LoginActivity.this.finish();
    }


    private void saveConfigInfo() {
        SharedPreferencesUtils.init(LoginActivity.this);
        SharedPreferencesUtils.setUserName(this, mUserText.getText().toString());
//        SharedPreferencesUtils.setPassword(mPasswordText.getText().toString().trim());
        SharedPreferencesUtils.setPassword(this, Utils.Md5(mPasswordText.getText().toString().trim()));
        SharedPreferencesUtils.setAutoLoginStatus(this, true);
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        if (null != manager) {
            manager.removeLoginListener(this);
        }

    }

    NoDoubleClickListener noDoubleClickListener = new NoDoubleClickListener() {
        @Override
        public void onNoDoubleClick(View v) {
            switch (v.getId()) {
                case R.id.login_btn:
                    long lastTime = SharedPreferencesUtils.getLastLoginTime(LoginActivity.this);
                    long time = System.currentTimeMillis();
                    if (time - lastTime > 5 * 60 * 1000) {
                        SharedPreferencesUtils.setLoginErrorCount(LoginActivity.this, 0);
                        SharedPreferencesUtils.setLastLoginTime(LoginActivity.this, time);
                        login();
                    } else {
                        int count = SharedPreferencesUtils.getLoginErrorCount(LoginActivity.this);
                        if (count >= 5) {
                            Notification.toast(LoginActivity.this, getResources().getString(R.string.error_times_tocast));
                        } else {
                            SharedPreferencesUtils.setLastLoginTime(LoginActivity.this, time);
                            login();
                        }
                    }
                    break;
                case R.id.login_register:
                    startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                    break;
                case R.id.login_forgetPassword:
                    Intent passIntent = new Intent();
                    /** type: 1 修改密码，0：忘记密码 */
                    passIntent.putExtra(Const.BUNDLE_DATA, 0);
                    passIntent.setClass(LoginActivity.this, ForgetActivity.class);
                    startActivity(passIntent);
                    break;
                case R.id.message_login:
                    Intent msgIntent = new Intent();
                    msgIntent.setClass(LoginActivity.this, MsgLoginActivity.class);
                    startActivity(msgIntent);
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    public void onError(int i, String s) {
        switch (i) {
            case 6208:
                Log.e(TAG,"离线状态下被其他终端踢下线... 再次登录");
                //离线状态下被其他终端踢下线
                // 再次掉登录接口
                GlobalUserData userData = new GlobalUserData();
                LoginBusiness.loginIm(userData.getEnvironemt() + GlobalContext.getAccountId(), userData.getUserSig(), LoginActivity.this);
                break;
            case 6200:
                if (null != pDialog && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                Notification.toast(LoginActivity.this, getString(R.string.login_error_timeout));
                break;
            default:
                if (null != pDialog && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                Notification.toast(LoginActivity.this, "【登录失败，错误码】：" + i);
                break;
        }
    }

    @Override
    public void onSuccess() {
        intoMainActivity();
    }
}
